package 栈题.中缀表达式转后缀不包含括号;


import java.util.LinkedList;
/**
 * 不带括号的方法
 */
public class Test {
    static int priority(char c) throws Exception {
        return switch (c) {
            case '*', '/' -> 2;
            case '+', '-' -> 1;
            default -> throw new IllegalAccessException("不合法的运算符: " + c);
        };

    }

    static String infixToSuffix(String exp) throws Exception {
        LinkedList<Character> stack = new LinkedList<>();
        StringBuilder sb = new StringBuilder(exp.length());
        for (int i = 0; i < exp.length(); i++) {
            char c = exp.charAt(i);
            switch (c) {
                case '*', '/', '+', '-' -> {
                    if (stack.isEmpty()) {
                        stack.push(c);
                    } else {
                        if (priority(c) > priority(stack.peek())) {
                            stack.push(c);
                        } else {
                            while (!stack.isEmpty() && priority(stack.peek()) >= priority(c)) {
                                sb.append(stack.pop());
                            }
                            stack.push(c);
                        }
                    }
                }
                default -> sb.append(c);
            }
        }
        while (!stack.isEmpty()) {
            sb.append(stack.pop());
        }
        return sb.toString();
    }


    public static void main(String[] args) throws Exception {
        System.out.println(infixToSuffix("1+2*3"));
    }
}
